package com.company.woye.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * 网络相关
 */
public class NetWorkUtils {
    //API版本23以下时调用此方法进行检测
    //因为API23后getNetworkInfo(int networkType)方法被弃用
    public static boolean checkNetState_21(Context context) {
        try {
            //步骤1：通过Context.getSystemService(Context.CONNECTIVITY_SERVICE)获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //步骤2：获取ConnectivityManager对象对应的NetworkInfo对象
            //NetworkInfo对象包含网络连接的所有信息
            //步骤3：根据需要取出网络连接信息
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            Boolean isWifiConn = networkInfo.isConnected();
            //获取移动数据连接的信息
            networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            Boolean isMobileConn = networkInfo.isConnected();
            System.out.println("Wifi是否连接:" + isWifiConn + " 移动数据是否连接:" + isMobileConn);
            return isWifiConn || isMobileConn;
        } catch (Exception e) {
            Log.d("NetWorkUtils", "checkNetState_21" + e.getMessage());
            return true;
        }
    }


    //API版本23及以上时调用此方法进行网络的检测
    //步骤非常类似
    public static boolean checkNetState_21orNew(Context context) {
        //获得ConnectivityManager对象
        boolean isConnect = false;
        try {
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取所有网络连接的信息
            Network[] networks = new Network[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                networks = connMgr.getAllNetworks();
            }
            //用于存放网络连接信息
            StringBuilder sb = new StringBuilder();
            //通过循环将网络信息逐个取出来
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    networkInfo = connMgr.getNetworkInfo(networks[i]);
                }
                if (isConnect == false) isConnect = networkInfo.isConnected();

            }
            return isConnect;
        } catch (Exception e) {
            Log.d("NetWorkUtils", "checkNetState_21orNew" + e.getMessage());
            return false;
        }
    }
}
